package cn.torna.tornaexample.controller.product;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriUtils;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * 演示导出
 * 注意，如果是前端直接跨域请求，需要在跨域设置addExposedHeader
 * corsConfiguration.addExposedHeader("Content-Disposition");
 * 参考：cn.torna.tornaexample.config.ExampleConfig
 */
@Api(value = "产品模块", position = -1)
@RestController
public class ExportController {

    @ApiOperation(value = "导出")
    @GetMapping("export")
    public ResponseEntity<byte[]> download() throws IOException {

        HttpHeaders headers = new HttpHeaders();
        // 假设下载classpath下的application.properties文件
        ClassPathResource resource = new ClassPathResource("/application.properties");

        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", resource.getFilename());

        return ResponseEntity
                .ok()
                .headers(headers)
                .body(IOUtils.toByteArray(resource.getInputStream()));
    }

    @ApiOperation(value = "导出zip")
    @GetMapping("exportZip")
    public ResponseEntity<byte[]> download2() throws IOException {

        HttpHeaders headers = new HttpHeaders();
        // 假设下载classpath下的application.properties文件
        ClassPathResource resource = new ClassPathResource("/res.zip");

        headers.setContentType(MediaType.valueOf("application/zip"));
        headers.setContentDispositionFormData("attachment", resource.getFilename());

        return ResponseEntity
                .ok()
                .headers(headers)
                .body(IOUtils.toByteArray(resource.getInputStream()));
    }

    @ApiOperation(value = "导出excel")
    @GetMapping("exportExcel")
    public ResponseEntity<byte[]> download3() throws IOException {
        HttpHeaders headers = new HttpHeaders();
        File file = new File("D:/data.xlsx");
        InputStream inputStream = FileUtils.openInputStream(file);
        headers.setContentType(MediaType.valueOf("application/octet-stream;charset=UTF-8"));
        headers.setContentDispositionFormData("attachment", file.getName());
        return ResponseEntity
                .ok()
                .headers(headers)
                .body(IOUtils.toByteArray(inputStream));
    }

    @ApiOperation(value = "导出excel2")
    @GetMapping("exportExcel2")
    public void download4(@ApiParam(hidden = true) HttpServletResponse response) throws IOException {
        File file = new File("D:/data.xlsx");
        InputStream inputStream = FileUtils.openInputStream(file);
        response.setContentType("application/x-msdownload;charset=UTF-8");
        response.setHeader("Content-disposition", "attachment; filename=" + file.getName());
        response.setHeader("Content-Length", String.valueOf(file.length()));
        IOUtils.copy(inputStream, response.getOutputStream());
    }

    @ApiOperation(value = "导出图片")
    @GetMapping("exportPng")
    public ResponseEntity<byte[]> exportPng() throws IOException {
        HttpHeaders headers = new HttpHeaders();
        // 假设下载classpath下的application.properties文件
        ClassPathResource resource = new ClassPathResource("/test.png");

        headers.setContentType(MediaType.IMAGE_PNG);
        headers.setContentDispositionFormData("attachment", resource.getFilename());

        return ResponseEntity
                .ok()
                .headers(headers)
                .body(IOUtils.toByteArray(resource.getInputStream()));
    }

    /**
     * 通过produces 告知浏览器我要返回的媒体类型
     */
    @GetMapping(value = "/getImage")
    @ApiOperation(value = "获取图片", notes = "返回一个图片流，页面展示图片")
    public void getImage2(
            @ApiParam(value = "文件类型，png/jpeg", example = "png")
            @RequestParam(defaultValue = "png") String type, HttpServletResponse response) throws IOException {
        ClassPathResource resource = new ClassPathResource("/test." + type);
        String contentType;
        switch (type) {
            case "jpeg":
            case "jpg":
                contentType = MediaType.IMAGE_JPEG_VALUE;
                break;
            case "gif":
                contentType = MediaType.IMAGE_GIF_VALUE;
                break;
            default: {
                contentType = MediaType.IMAGE_PNG_VALUE;
            }
        }
        response.setContentType(contentType);
        // try包裹，自动close
        try (InputStream inputStream = resource.getInputStream()) {
            IOUtils.copy(inputStream, response.getOutputStream());
        }
    }

    /**
     * 返回pdf流，浏览器预览pdf
     * @param response
     * @throws IOException
     */
    @GetMapping("/pdf/view")
    public void test(HttpServletResponse response) throws IOException {
        String str = "D:/对接技术要求.pdf";
        FileInputStream fileInputStream = new FileInputStream(str);
        // 浏览器尝试打开,支持office online或浏览器预览pdf功能
        String filename = UriUtils.encode(str.substring(str.lastIndexOf("/") + 1), StandardCharsets.UTF_8);
        response.addHeader("Content-Disposition", "inline; filename=" + filename);
        response.setContentType("application/pdf");
        IOUtils.copy(fileInputStream, response.getOutputStream());
    }
}
